package cn.tedu.oa.sys.service.impl;

import cn.tedu.oa.common.annotation.LogAnnotation;
import cn.tedu.oa.common.exception.ServiceException;
import cn.tedu.oa.common.service.impl.BaseServiceImpl;
import cn.tedu.oa.common.util.ShiroUtils;
import cn.tedu.oa.common.vo.JsonResult;
import cn.tedu.oa.sys.dao.DepartmentDao;
import cn.tedu.oa.sys.dao.UserDao;
import cn.tedu.oa.sys.dao.UserRoleDao;
import cn.tedu.oa.sys.entity.Department;
import cn.tedu.oa.sys.entity.User;
import cn.tedu.oa.sys.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private DepartmentDao departmentDao;
    @Autowired
    private UserRoleDao userRoleDao;
    @Override
    public User getUserByUsername(String username) {
        if (StringUtils.isEmpty(username)) {
            throw new ServiceException("用户名为空");
        }
        return userDao.getUserByUsername(username);
    }

    /**
     * 验证条件异常
     * @param user 用户信息
     * @param method 添加 / 修改
     */
    @LogAnnotation("用户：添加修改异常验证")
    private void validate(User user,String method) {
        if (user == null) {
            throw new ServiceException(method + "失败:提交的用户信息为空");
        }
        /*修改时验证id,添加时不验证(禁止修改密码)*/
        if ("修改".equals(method)) {
            if (user.getId() == null || user.getId() < 0) {
                throw new ServiceException(method + "失败：用户id传递错误");
            }
            User userById = getUserById(user.getId());
            if (userById == null) {
                throw new ServiceException(method + "失败：用户不存在");
            }
        }
        if (user.getUsername() == null || StringUtils.isEmpty(user.getUsername().trim())) {
            throw new ServiceException(method + "失败：用户名为空");
        }
        if (user.getDeptId() == null || user.getDeptId() < 0) {
            throw new ServiceException(method + "失败：部门id为空或者为负数");
        }
        /*验证该部门是否存在*/
        Department deptById = getDeptById(user.getDeptId());
        if (deptById == null) {
            throw new ServiceException(method + "失败：没有这个部门");
        }
        if ("添加".equals(method)) {
            /*添加时验证密码，修改不验证*/
            if (user.getPassword() == null || StringUtils.isEmpty(user.getPassword().trim())) {
                throw new ServiceException(method + "失败：密码为空");
            }
            /*添加时用户名是否存在，修改不验证*/
            User userByUsername = getUserByUsername(user.getUsername());
            if (userByUsername != null) {
                throw new ServiceException(method + "失败：用户名已存在");
            }
        }
        if (user.getName() == null || StringUtils.isEmpty(user.getName().trim())) {
            throw new ServiceException(method + "失败：姓名为空");
        }
        if (user.getMobile() == null || StringUtils.isEmpty(user.getMobile().trim())) {
            throw new ServiceException(method + "失败：手机号为空");
        }
        if (user.getEmail() == null || StringUtils.isEmpty(user.getEmail().trim())) {
            throw new ServiceException(method + "失败：邮箱为空");
        }
    }

    private Department getDeptById(Integer deptId) {
        return departmentDao.get(deptId);
    }

    @Override
    public void add(User user) {
        validate(user,"添加");
        /*密码加密加盐*/
        user.setSalt(ShiroUtils.getSalt());
        user.setPassword(ShiroUtils.encryption(user.getPassword(), user.getSalt()));
        /*启用/禁用处理*/
        handlerValid(user);
        /*添加人*/
        try {
            user.setAddUser(ShiroUtils.getPrincipal().getName());
        } catch (Exception e) {
            throw new ServiceException("获取登录用户异常");
        }
        /*添加时间*/
        user.setAddTime(new Date());
        /*删除状态：0 正常 1 以删除*/
        user.setIsdel(0);
        userDao.add(user);
    }


    @Override
    public void update(User user) {
        validate(user,"修改");
        /*启用/禁用处理*/
        handlerValid(user);
        /*修改人*/
        try {
            user.setUpdateUser(ShiroUtils.getPrincipal().getName());
        } catch (Exception e) {
            throw new ServiceException("获取登录用户异常");
        }
        /*修改时间*/
        user.setUpdateTime(new Date());
        userDao.update(user);
    }

    /*启用/禁用处理*/
    private void handlerValid(User user) {
        if (user != null && user.getValid() == null) {
            user.setValid(1);
        }else {
            user.setValid(0);
        }
    }

    @Override
    public List<User> getUserPagerList(String criteria, Integer pageNo, Integer pageSize) {
        if (pageNo == null || pageNo < 1 || pageSize == null || pageSize < 1) {
            throw new IllegalArgumentException("参数不合法，请联系运维人员");
        }
        /*假设pageSize=10*/
        /*1 (1-1) x 10 + 1 = 1*/
        /*2 (2-1) x 10 + 1 = 11*/
        /*3 (3-1) x 10 + 1 = 21*/ /*@ming*/
        int startIndex = (pageNo - 1) * pageSize + 1;
        /*1 1 + 10 - 1 = 10*/
        /*2 11 + 10 - 1 = 20*/
        /*3 21 + 10 - 1 = 30*/ /*@ming*/
        int endIndex = startIndex + pageSize - 1;
        List<User> list = userDao.getUserPagerList(criteria, startIndex, endIndex);
        if (list == null) {
            throw new ServiceException("没有查询到数据");
        }
        return list;
    }

    @Override
    public JsonResult getPagerJsonResult(String criteria, Integer pageNo, Integer pageSize) {
        if (criteria != null) {
            criteria = criteria.trim();
        }
        List<User> list = this.getUserPagerList(criteria, pageNo, pageSize);
        int rowCount = this.getRowCount(criteria);
        JsonResult result = new JsonResult();
        result.setCount(rowCount);
        result.setData(list);
        return result;
    }

    @Override
    public JsonResult getDeptIdAndName() {
        JsonResult result = new JsonResult();
        List<Department> list = userDao.getDeptIdAndName();
        result.setData(list);
        return result;
    }

    @Override
    public void insertRoleByUser(Integer userId, Integer[] roleId, Integer isdel) {
        if(userId==null)
            throw new IllegalArgumentException("用户信息不能为空");
        if(StringUtils.isEmpty(userId.toString()))
            throw new IllegalArgumentException("角色不能为空");
        if(roleId==null||roleId.length==0)
            throw new IllegalArgumentException("必须为用户分配一个角色资源");
        //2.保存
        userRoleDao.insertRoleByUser(
                userId,
                roleId,
                isdel);
    }

    @Override
    public int updatePasswordById(Integer id, String password, String newPassword, String confirmPassword) {
        User user = userDao.get(id);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        if (password == null ) {
            throw new IllegalArgumentException("用户密码不正确");
        }

        /*密码加密加盐*/
        User user1 = userDao.get(user.getId());
        String encryption = ShiroUtils.encryption(password, user1.getSalt());
        /*判断旧密码是否正确*/
        if (!encryption.equals(user1.getPassword())){
            throw new IllegalArgumentException("输入密码不正确");
        }
        /*判断新密码与确认密码是否一致*/
        if (!newPassword.equals(confirmPassword)){
            throw new IllegalArgumentException("输入密码与新密码不一致");
        }
        /*对新密码加密*/
        String encryption1 = ShiroUtils.encryption(confirmPassword, user.getSalt());
        /*根据id修改密码*/
        int row = userDao.updatePasswordById(user.getId(), encryption1);
        return row;
    }

    @Override
    public User getUserById(Integer id) {
        if (id == null || id < 0) {
            return null;
        }
        return userDao.get(id);
    }
}
